/*
 * Keyboard class represents a device capable of capturing user character input
 * Keyboard subscribes to the Device interface
 * */

package system.device;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import cpu.components.DeviceUnit;
import cpu.datatypes.*;
import cpu.interfaces.*;
import ui.Console;
import ui.Printer;

public class Keyboard implements Device, KeyListener {

	private DeviceUnit controller;
	
	boolean waitForInput = false;
	int currentKey;
	
	public Keyboard( Console console, Printer printer ) {
		console.window.addKeyListener( this );
		printer.text.addKeyListener( this );
	}
	
	public void enroll( int id, cpu.components.DeviceUnit controller ) {
		this.controller = controller;
		controller.enroll( id, this );
	}
	
	public void get( ) {
		// controller.DBR <- Device(controller.DID)
		
		waitForInput = true;
		while( waitForInput ) {
			Thread t = Thread.currentThread();
			try {
				t.sleep(100);
			} catch(Exception ex) {
				
			}
		}
		controller.DBR.fromSignedInteger( currentKey );
	}
	public void put( ) {
		// Device(controller.DID) <- controller.DBR;
	}
	public void status( ) {
		// controller.DSR <- Device(controller.DID)
		// Note that this is a status query
	}
	public void keyPressed(KeyEvent keyEvent) { 
		
	}
	public void keyReleased(KeyEvent keyEvent) { 
		
	}
	public void keyTyped(KeyEvent keyEvent) {
		//System.out.println( "key typed: " + keyEvent.getKeyChar( ) );
		currentKey = keyEvent.getKeyChar( );
		if( waitForInput )
			waitForInput = false;
	}

}